package dao.hibernate;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.hibernate.Session;

import utils.Functions;

import model.Poll;
import model.User;
import dao.DAOUser;

public class DAOUserHBM extends DAOHibernate implements DAOUser {

	@Override
	public User get(int id) {
		Session session = connect();
		User user = (User)session.get(User.class, id);
		close(session);
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<User> load(String name) {
		Session session = connect();
		ArrayList<User> users = (ArrayList<User>) session.createQuery("FROM User WHERE name = '" + name + "'").list();	
		close(session);
		return users;
	}

	@Override
	public void remove(User user) {
		Session session = connect();
		session.delete(user);	
		close(session);
		user.setID(0);
	}

	@Override
	public void saveOrUpdate(User user) {
		Session session = connect();
		session.saveOrUpdate(user);
		close(session);
	}

	@Override
	public ArrayList<User> load() {
		Session session = connect();
		ArrayList<User> users = (ArrayList<User>) session.createQuery("FROM User").list();	
		close(session);
		return users;
	}
	@Override
	 public User login(String name, String password) {
	  Session session = connect();
	  User result;
	  try {
	   result = (User)session.createQuery("FROM User WHERE name = '" + name + "' AND pass = '" + password +"'").uniqueResult();
	   result.setLastConnectDate(Functions.now());
	  }
	  catch (Exception e) {
	   result = null;
	  }
	  finally {
	   close(session);
	  }
	  if (null != result){
		//update last connect date
		this.saveOrUpdate(result);
	  }
	  return result;
	 }

	@Override
	public User getByName(String name) {
		Session session = connect();
		User user = (User) session.createQuery("FROM User WHERE name = '" + name + "'").uniqueResult();	
		close(session);
		return user;
	}
}
